#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年7月30日

@author: chenyongbing
'''
import os,datetime,sys,time

import argparse,re
import commands
current_dir = os.path.split(os.path.realpath(__file__))[0]
import logging
class BuildProject(object):
    '''
        自动化 build java代码
        
    '''


    def __init__(self,project='',opath='',branch='master',base='2.4.3',gitpath='/home/zhima/java/build/'):
        '''
        Constructor
        '''
        today = datetime.date.today().strftime('%Y-%m-%d') 
        self.project = project
        self.branch = branch
        self.path = gitpath
        self.opath = opath+'/'+today
        commands.getoutput("mkdir -p %s"%self.opath)
        tag =  datetime.date.today().strftime('%m%d')
        self.gitpath = gitpath
        self.base = base
        self.msgs = []
        
        self.propath = self.opath+'/'+self.project+'-%s.%s'%(branch,tag)
        
    
    def pull_build_base(self,base_commit = None):
        logging.info('Start To Pull base with branch %s'%self.base)
        os.chdir(os.path.join(self.gitpath,'zm-base-%s'%self.base))
        if base_commit !=None:
            self.git_checkout(branch=base_commit)
        else:
            self.git_checkout(branch=self.base)
        output = self.git_pull()
        commit_log = self.git_commit_log()
        if not re.search('Already up-to-date',output):
            self.build()
        self.msgs.append('zm-base,%s,%s'%(self.base,commit_log))
        
        
    def pull_build(self,commit=None):
        logging.info('Start To Pull %s with branch %s'%(self.project,self.branch))
        os.chdir(os.path.join(self.gitpath,self.project))
        self.git_pull()
        if commit!=None:
            self.git_checkout(commit)
        else:
            self.git_checkout()
        self.git_pull()
        self.build()
        commit_log = self.git_commit_log()
        self.msgs.append('%s,%s,%s'%(self.project,self.branch,commit_log))
        self.copyFiles()
        
        
    def git_commit_log(self):
        commit_log = os.popen('git log').read().split('\n')[0]
        return commit_log
    def git_checkout(self,branch=None):
        if branch==None:
            branch = self.branch
        cmd = 'git checkout %s'%branch
        out = commands.getoutput(cmd)
        print out
    def git_pull(self):
        cmd = 'git pull'
        out = commands.getoutput(cmd)
        return out
        
    def build(self):
        cmd = 'sh build.sh'
        out = commands.getoutput(cmd)
        print out
    def copyFiles(self):
        if self.project == 'zm-ws' or re.search('zm-ws',self.project):
            cmd = 'mkdir -p %s'%self.propath
            commands.getoutput(cmd)
            
            cmd = 'cp %s/target/*.war %s'%(self.path+'/'+self.project,self.propath)
            
            commands.getoutput(cmd)
            cmd = 'cp -r %s/src/main/resources %s/'%(self.path+'/'+self.project,self.propath)
            print cmd
            out = commands.getoutput(cmd)
            
            
        else:
            self.libpath = self.propath+'/libs/'
            self.logpath = self.propath+'/log/'
            self.binpath = self.propath+'/bin/'
            if not os.path.exists(self.libpath):
                cmd = 'mkdir -p %s'%self.libpath        
            else:
                cmd = 'rm -rf %s/*'%self.libpath
            commands.getoutput(cmd)
            if not os.path.exists(self.logpath):
                cmd = 'mkdir -p %s'%self.logpath
                commands.getoutput(cmd)
            if not os.path.exists(self.binpath):
                cmd = 'mkdir -p %s'%self.binpath
            else:
                cmd = 'rm -rf %s/*'%self.binpath
            commands.getoutput(cmd)
            
            if os.path.exists(self.propath+'/resources'):
                cmd = 'rm rf %s'%(self.propath+'/resources')
                commands.getoutput(cmd)
            
            cmd = 'cp %s/target/*.jar %s'%(self.path+'/'+self.project,self.libpath)
            print cmd
            out = commands.getoutput(cmd)
            print out
            #if len(os.listdir(self.opath+'/'+self.project))>1:
            #    cmd = 'cp %s/target/dependency/* %s'%(self.path+'/'+self.project,self.libpath)
            #else:
            cmd = 'cp %s/target/dependency/* %s'%(self.path+'/'+self.project,self.libpath)        
            print cmd
            out = commands.getoutput(cmd)
            print out
            cmd = 'cp -r %s/src/main/resources %s/'%(self.path+'/'+self.project,self.propath)
            print cmd
            out = commands.getoutput(cmd)
            print out
        fr = open(self.propath+'/README','w')
        fr.write('\n'.join(self.msgs))
        fr.close()


    def get_branch_and_commit(self,projectPath = '/data/zhimind',gitPath = '/home/zhima/java/build',commit=None):
        rfile = projectPath+'/README'
        if not os.path.exists(rfile):
            logging.error('file %s not exists.'%(rfile))
            sys.exit()
    
        for line in open(rfile).read().split('\n'):
            lineList = line.split(',')
            if len(lineList)!=3:continue
            pj_name,pj_ver,pj_commit = lineList
            if pj_name == 'zm-base':
                pj_gitpath = gitPath + '/%s-%s'%(pj_name,pj_ver)
            else:
                pj_gitpath = gitPath +'/%s'%pj_name
                
            self.git_pull()
            if commit!=None:
                self.git_checkout(commit)
            else:
                logging.error('commit must not None')
                sys.exit()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('-p', metavar=u'build project', required=True)
    parser.add_argument('-b' ,  metavar=u'branch', required=True)
    parser.add_argument('-O',metavar=u'output path',required=True)
    parser.add_argument('--base',metavar=u'base branch',default='2.4.3')
    
    parser.add_argument('--tag',action='store_true',help='add tag')
    args = parser.parse_args()
    project = args.p
    branchStr = args.b
    opath = args.O
    baseStr = args.base
    tag = args.tag
    
    
    gitpath = '/home/zhima/java/build/'
    
    baseList = baseStr.split(',')
    if len(baseList)==1:
        base = baseList[0]
        base_commit = None
    else:
        base = baseList[0]
        base_commit = baseList[1]
    
    branchList = branchStr.split(',')
    if len(branchList)==1:
        branch = branchList[0]
        project_commit = None
    else:
        branch = branchList[0]
        project_commit = branchList[1]
    
    myBuildProject = BuildProject(project=project,branch=branch,opath=opath,base=base,gitpath=gitpath)
    if base!=None:
        myBuildProject.pull_build_base(base_commit = base_commit)
    myBuildProject.pull_build(commit=project_commit)
